<template>
  <div class="app-container">
    <div class="head-container">
      <!-- 搜索栏 -->
      <div style="display: flex;">
        <label class="el-form-item-label">料号</label>
        <el-input v-model.trim="query.productNo" clearable placeholder="料号" style="width: 185px;" class="filter-item" @keyup.enter.native="toQuery" @clear="toQuery" />
        <label class="el-form-item-label">客户</label>
        <el-input v-model.trim="query.receiverName" clearable placeholder="客户" style="width: 185px;" class="filter-item" @keyup.enter.native="toQuery" @clear="toQuery" />
        <!-- <label class="el-form-item-label">生产日期</label>
        <el-date-picker
          v-model="query.inboundTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          class="filter-item"
          @change="toQuery"
        /> -->
        <div style="margin-left: 5px;">
          <el-button size="mini" icon="el-icon-search" class="filter-item" type="success" @click="toQuery">搜索</el-button>
          <el-button size="mini" icon="el-icon-refresh-right" class="filter-item" type="warning" @click="reset">重置</el-button>
        </div>
      </div>
      <div style="display: flex;align-items: start;margin: 0 0 20px 0;gap: 10px;">
        <el-radio-group v-model="selected">
          <el-radio-button label="按料号设置" value="PRODUCTNO" />
          <el-radio-button label="按类型设置" value="CATEGORY" />
        </el-radio-group>
        <div style="display: flex;gap: 5px;">
          <el-button
            type="warning"
            size="mini"
            plain
            class="filter-item"
            icon="el-icon-box"
            :disabled="select_table.length === 0"
            @click="moveDialog = true"
          >移库至呆滞区</el-button>
          <el-button
            type="primary"
            size="mini"
            class="filter-item"
            icon="el-icon-download"
            plain
            :loading="btn.download"
            @click="downloadExcel"
          >下载</el-button>
        </div>
      </div>
      <!-- 表单渲染 -->
      <el-dialog title="移库至呆滞区" :visible.sync="moveDialog" width="28%" :before-close="handleClose" :close-on-click-modal="false">
        <el-form ref="formRef" :model="form" :rules="rules">
          <el-form-item label="移库单类型" prop="type" :label-width="formLabelWidth">
            <el-select v-model="form.type" style="width: 250px;" placeholder="请选择">
              <el-option
                v-for="item in dict.moveOrder_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.label !== '正常移库'"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="移库库区" prop="warehouse" :label-width="formLabelWidth">
            <el-select v-model="form.warehouse" style="width: 250px;" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.text"
                :value="item.value"
                :disabled="item.value !== 'JT15'"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="退库人员工号" prop="code" :label-width="formLabelWidth">
            <el-input v-model="form.code" style="width: 250px;" />
          </el-form-item>
          <el-form-item label="退库人员姓名" prop="name" :label-width="formLabelWidth">
            <el-input v-model="form.name" style="width: 250px;" />
          </el-form-item> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" :loading="btn.createBtn" @click="submit">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 列表渲染 -->
      <el-table ref="table" v-loading="loading" :data="list" size="small" style="width: 100%;" @selection-change="updateSelect" @select-all="handlerAll">
        <el-table-column type="selection" width="55" />
        <!-- <el-table-column prop="parentPalletId" label="母托ID" /> -->
        <el-table-column prop="parentPalletCode" label="母托编码" />
        <el-table-column prop="productNo" label="料号" />
        <el-table-column prop="productDescription" label="物料描述" />
        <el-table-column prop="partnerProductNo" label="客户物料编码" />
        <el-table-column prop="receiverName" label="客户名" />
        <el-table-column prop="qty" label="数量" />
        <el-table-column prop="inventoryAge" label="库龄" />
        <el-table-column prop="dullTimeDays" label="呆滞时间/slowing时间" />
        <el-table-column prop="isEstDull" label="是否呆滞/slowing">
          <template slot-scope="scope">
            {{ scope.row.isEstDull === 'dull' ? '呆滞' : scope.row.isEstDull }}
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <el-pagination
        :page-size.sync="query.size"
        :total="total"
        :current-page.sync="query.current"
        style="margin-top: 8px;"
        layout="total, prev, pager, next, sizes"
        @size-change="sizeChangeHandler($event)"
        @current-change="pageChangeHandler"
      />
    </div>
  </div>
</template>

<script>
import { createMoveOrderAPI } from '@/api/work/returnStock'
import { getListAPI, downloadFileAPI } from '@/api/work/idleQuery'
import { getWareHouseAPI } from '@/api/work/moveStorage'
export default {
  name: 'IdleQuery',
  dicts: ['moveOrder_type'],
  data() {
    return {
      query: {
        ruleType: 'PRODUCTNO',
        current: 1,
        size: 10
      },
      list: [],
      options: [],
      total: 0,
      loading: false,
      selected: '按料号设置',
      formLabelWidth: '120px',
      moveDialog: false,
      form: {},
      select_table: [],
      btn: {
        createBtn: false,
        download: false
      },
      rules: {
        type: [
          { required: true, message: '请选择移库单类型', trigger: 'change' }
        ],
        warehouse: [
          { required: true, message: '请选择移库库区', trigger: 'change' }
        ],
        code: [
          { required: true, message: '请输入退库人员工号', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入退库人员姓名', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    selectedValue() {
      switch (this.selected) {
        case '按类型设置':
          return 'CATEGORY'
        case '按料号设置':
          return 'PRODUCTNO'
        default:
          return ''
      }
    }
  },
  watch: {
    selectedValue(newVal, oldVal) {
      if (newVal === 'CATEGORY') {
        this.query.ruleType = 'CATEGORY'
        this.query.current = 1
        this.toQuery()
      } else if (newVal === 'PRODUCTNO') {
        this.query.ruleType = 'PRODUCTNO'
        this.query.current = 1
        this.toQuery()
      }
    },
    moveDialog(newVal) {
      if (newVal) {
        const matchedItem = this.dict.moveOrder_type.find(item => item.value === '1')
        const secondItem = this.options.find(item => item.value === 'JT15')
        if (matchedItem) {
          // 将中文标签设置到表单的 type 中
          this.form.type = matchedItem.label
        } else {
          // 如果没有找到匹配项，可以设置为默认值或空
          this.form.type = ''
        }
        if (secondItem) {
          this.form.warehouse = secondItem.text
        } else {
          this.form.warehouse = ''
        }
      }
    }
  },
  mounted() {
    this.getWareHouse()
    this.toQuery()
  },
  methods: {
    reset() {
      this.query = {
        ruleType: 'PRODUCTNO',
        current: 1,
        size: 10
      }
      this.toQuery()
    },
    toQuery() {
      this.getList()
    },
    async getWareHouse() {
      const res = await getWareHouseAPI()
      if (res.result === 'OK') {
        this.options = res.data
      } else {
        return this.$message.warning(res.data)
      }
    },
    async getList() {
      try {
        this.loading = true
        const res = await getListAPI(this.query)
        this.list = res.data.content
        this.total = res.data.totalElements
      } finally {
        this.loading = false
      }
    },
    async downloadExcel() {
      try {
        this.btn.download = true
        const res = await downloadFileAPI(this.selectedValue)
        if (res && res instanceof Blob) {
          this.downloadFile(res)
        } else {
          this.$message.warning('文件下载失败，返回数据不是有效的文件内容')
        }
      } finally {
        this.btn.download = false
      }
    },
    downloadFile(obj) {
      const url = window.URL.createObjectURL(new Blob([obj]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      if (this.selected === '按类型设置') {
        this.fileName = `类型模板表_${new Date().getTime()}.xlsx`
      } else if (this.selected === '按料号设置') {
        this.fileName = `料号模板表_${new Date().getTime()}.xlsx`
      }
      link.setAttribute('download', this.fileName)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    },
    sizeChangeHandler(e) {
      this.query.size = e
      this.query.current = 1
      this.getList()
    },
    pageChangeHandler(e) {
      this.query.current = e
      this.getList()
    },
    handleClose() {
      this.moveDialog = false
    },
    handlerAll(val) {
      if (val) {
        this.select_table = val
      } else {
        this.select_table = []
      }
    },
    updateSelect(val) {
      if (val) {
        this.select_table = val
      } else {
        this.select_table = []
      }
    },
    submit() {
      this.$refs.formRef.validate(async(valid) => {
        if (valid) {
          this.btn.createBtn = true
          const submitForm = {
            // applicantEmployeeNo: this.form.code,
            // applicantName: this.form.name,
            moveTo: 'JT15',
            parentPalletCodeList: this.select_table.map(item => item.parentPalletCode),
            moveWareHouseOrderType: 1
          }
          console.log(submitForm)
          const res = await createMoveOrderAPI(submitForm)
          if (res.result === 'OK') {
            this.btn.createBtn = false
            this.$message.success('创建成功')
            this.$router.push('/storageManagement/moveOrder')
          } else {
            this.btn.createBtn = false
            this.$message.warning(res.data)
          }
        } else {
          // 表单验证失败，提示用户
          // this.$message.error('请填写完整信息')
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
</style>
